package io.renren.modules.cuttingcur.service.impl;

import com.alibaba.fastjson.JSONObject;
import io.renren.modules.cuttingcur.entity.OldCuttinginfoEntity;
import io.renren.modules.testrestful.entity.DevicesInfoResponse;
import io.renren.modules.testrestful.service.impl.UsersServiceImpl;
import lombok.Data;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.cuttingcur.dao.CuttingmachineCurdataDao;
import io.renren.modules.cuttingcur.entity.CuttingmachineCurdataEntity;
import io.renren.modules.cuttingcur.service.CuttingmachineCurdataService;
import org.springframework.web.client.RestTemplate;


@Service("cuttingmachineCurdataService")
public class CuttingmachineCurdataServiceImpl extends ServiceImpl<CuttingmachineCurdataDao, CuttingmachineCurdataEntity> implements CuttingmachineCurdataService {

    @Autowired
    CuttingmachineCurdataDao cuttingmachineCurdataDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CuttingmachineCurdataEntity> page = this.page(
                new Query<CuttingmachineCurdataEntity>().getPage(params),
                new QueryWrapper<CuttingmachineCurdataEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CuttingmachineCurdataEntity> listAll() {
        return cuttingmachineCurdataDao.listAll();
    }

    @Override
    public List<CuttingmachineCurdataDao> getCuttingMachine() {
        return cuttingmachineCurdataDao.getCuttingMachine();
    }

    @Override
    public List<OldCuttinginfoEntity> listCuttinginfo() {
        System.out.println(cuttingmachineCurdataDao.listCuttinginfo());
        return cuttingmachineCurdataDao.listCuttinginfo();
    }


    @Data
    public static class CutData {
        private String deviceName;
        private String deviceCutStatus;
        private String timestamp;
    }



    @Override

    public List<CutData> cutNew() {
        System.out.println(cuttingmachineCurdataDao.cutNew());
        return cuttingmachineCurdataDao.cutNew();
    }


    @Override
    public List<OldCuttinginfoEntity> getCuttingInfoById(String deviceId) {
        return cuttingmachineCurdataDao.getCuttingInfoByDeviceId(deviceId);
    }

    @Override
    public int updateByDeviceId(String deviceId, String deviceName, String deviceType, String deviceProfileName, String deviceProtocol, String createdTime) {
        return cuttingmachineCurdataDao.updateByDeviceId(deviceId, deviceName, deviceType, deviceProfileName, deviceProtocol, createdTime);
    }


    @Data
    public static class ReHeader {
        private String username;
        private String password;
    }

    @Autowired
    private RestTemplate restTemplate;

    //    @Scheduled(cron = "0/5 * * * * ?")
    public Object getToken() {
        RestTemplate restTemplate = new RestTemplate();

        // 获取token
        UsersServiceImpl.ReHeader reHeader = new UsersServiceImpl.ReHeader();
        reHeader.setUsername("716_api@thingsboard.com");
        reHeader.setPassword("716Api@2024");
        String url = "https://thingsboard.cmhijs.cn:8443/api/auth/login";
        String token = restTemplate.postForObject(url, reHeader, String.class);
        JSONObject jsonObject = JSONObject.parseObject(token);
        String token1 = jsonObject.getString("token");
        return token1.toString();
    }
 //
//https://thingsboard.cmhijs.cn:8443/api/customer/52a9aac0-c949-11ed-826f-2d2aeab65199/deviceInfos?pageSize=10&page=0&sortProperty=createdTime&sortOrder=DESC&deviceProfileId=87564350-1eb7-11ee-9e2f-eba35a8e94c4
    //获取设备信息
    @Async("screenTaskExecutor")
//    @Scheduled(cron = "0/5 * * * * ?")
    public String getAllDevices() throws InterruptedException {
        HttpHeaders headers = new HttpHeaders();

//https://thingsboard.cmhijs.cn:8443/api/customer/52a9aac0-c949-11ed-826f-2d2aeab65199/deviceInfos?pageSize=10&page=0&sortProperty=createdTime&sortOrder=DESC&deviceProfileId=87564350-1eb7-11ee-9e2f-eba35a8e94c4
//        String url = "https://thingsboard.cmhijs.cn/api/tenant/deviceInfos?pageSize=100&page=0&sortProperty=createdTime&sortOrder=DESC&deviceProfileId=";
        String url = "https://thingsboard.cmhijs.cn:8443/api/customer/52a9aac0-c949-11ed-826f-2d2aeab65199/deviceInfos?pageSize=10&page=0&sortProperty=createdTime&sortOrder=DESC&deviceProfileId=87564350-1eb7-11ee-9e2f-eba35a8e94c4";
        RestTemplate restTemplate = new RestTemplate();

        String token = getToken().toString();
        String val = "Bearer " + token;

        headers.set("x-authorization", val);
        HttpEntity<String> httpEntity = new HttpEntity<>(headers);

        ResponseEntity<DevicesInfoResponse> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, DevicesInfoResponse.class);
        System.out.println(responseEntity);
        DevicesInfoResponse dr = responseEntity.getBody();
        System.out.println(dr);

        for (DevicesInfoResponse.DriverData driverData : dr.getData()) {
            System.out.println(driverData);//dr.getData:返回一个设备信息列


            /*设备信息

            {
	"data": [{
			"id": {
				"entityType": "DEVICE",
				"id": "9a606930-f464-11ed-bbb0-dde55e1f139a"
			},
			"createdTime": 1684294844227,
			"additionalInfo": {
				"gateway": false,
				"overwriteActivityTime": false,
				"description": ""
			},
			"tenantId": {
				"entityType": "TENANT",
				"id": "30018d00-ce10-11ed-bbb0-dde55e1f139a"
			},
			"customerId": {
				"entityType": "CUSTOMER",
				"id": "13814000-1dd2-11b2-8080-808080808080"
			},
			"name": "智能制造中心设备稼动率数据——测试",
			"type": "智能制造中心-KepServer-TEST",
			"label": "",
			"deviceProfileId": {
				"entityType": "DEVICE_PROFILE",
				"id": "a2a70c30-e185-11ed-bbb0-dde55e1f139a"
			},
			"deviceData": {
				"configuration": {
					"type": "DEFAULT"
				},
				"transportConfiguration": {
					"type": "DEFAULT"
				}
			},
			"firmwareId": null,
			"softwareId": null,
			"externalId": null,
			"customerTitle": null,
			"customerIsPublic": false,
			"deviceProfileName": "智能制造中心-KepServer-TEST",
			"active": false
		}],
	"totalPages": 1,
	"totalElements": 9,
	"hasNext": false
}
             */


            //设备ID

            String deviceId = driverData.getId().getId();

            //设备名称
            String deviceName = driverData.getName();
            //设备类型
            String deviceType = driverData.getType();
            //设备配置
            String deviceProfileName = driverData.getDeviceProfileName();
            //创建时间
            String createdTime = driverData.getCreatedTime().toString();
//            System.out.println("设备名称："+deviceName+",设备ID："+deviceId+",设备类型："+deviceType+",设备配置："+deviceProfileName+",创建时间："+createdTime);
//            System.out.println("--------------------------------------------");
            //设备信息存入数据库
            OldCuttinginfoEntity oldCuttinginfoEntity = new OldCuttinginfoEntity();
            oldCuttinginfoEntity.setId(UUID.randomUUID().toString());
            oldCuttinginfoEntity.setDeviceId(deviceId);
            oldCuttinginfoEntity.setDeviceName(deviceName);
            oldCuttinginfoEntity.setDeviceType(deviceType);
            oldCuttinginfoEntity.setDeviceProfileName(deviceProfileName);
            oldCuttinginfoEntity.setCreatedTime(createdTime);
            //存入数据库前先判断是否存在该设备
            List<OldCuttinginfoEntity> cuttinginfoEntities = cuttingmachineCurdataDao.getCuttingInfoByDeviceId(deviceId);
            if (cuttinginfoEntities.size() == 0) {
//                cuttingmachineCurdataDao.postCuttingData(cuttinginfoEntity);
                System.out.println("设备："+deviceName+"存入数据库");
            } else {
                System.out.println("该设备已存在");
            }
//            cuttingmachineCurdataDao.postCuttingData(cuttinginfoEntity);
//            devicesInfoDao.postDevicesInfo(devicesInfoEntity);
        }
        return dr.toString();
    }
}